<?php
/**
 * @package general
 */
class Dropdown extends StringField {
	
	protected $enum_class, $enum, $default;
	
	private static $default_search_filter_class = 'ExactMatchFilter';
	
	/**
	 * Create a new DropdownList field.
	 * 
	 * Example usage in {@link DataObject::$db} with dropdown dataobject name 
	 * notation ('Val1' is default)
	 *
	 * <code>
	 *  "MyField" => "Dropdown('DropdownList', 'Val1')"
	 * </code>
	 * 
	 * @param class: A dataobject name with list of options.
	 * @param string The default option, which is either NULL or one of the 
	 *				 items in the dropdownlist.
	 */
	public function __construct($name = null, $class = NULL, $default = NULL, $size = 50) {
		$this->enum_class = $class;
		$this->size = $size ? $size : 50;
		parent::__construct($name);
	}
	
	/**
 	 * (non-PHPdoc)
 	 * @see DBField::requireField()
 	 */
	public function requireField() {
		$parts = array(
			'datatype'=>'varchar',
			'precision'=>$this->size,
			'character set'=>'utf8',
			'collate'=>'utf8_general_ci',
			'default' => Convert::raw2sql($this->default), 
			'arrayValue'=>$this->arrayValue
		);
		
		$values = array(
			'type' => 'varchar',
			'parts' => $parts
		);
			
		DB::requireField($this->tableName, $this->name, $values);
	}
	
	/**
	 * Return a dropdown field suitable for editing this field.
	 *
	 * @return DropdownField
	 */
	public function formField($title = null, $name = null, $hasEmpty = false, $value = "", $form = null,
			$emptyString = null) {

		if(!$title) $title = $this->name;
		if(!$name) $name = $this->name;

		$field = DropdownField::create($name, $title, $this->enumValues($hasEmpty), $value, $form);
		if($hasEmpty) {
			$field->setEmptyString($emptyString);
		}

		return $field;
	}

	/**
	 * @return DropdownField
	 */
	public function scaffoldFormField($title = null, $params = null) {
		return $this->formField($title);
	}

	/**
	 * @param string
	 *
	 * @return DropdownField
	 */
	public function scaffoldSearchField($title = null) {
		$anyText = _t('Dropdown.ANY', 'Any');
		return $this->formField($title, null, true, '', null, "($anyText)");
	}
	
	/**
	 * Returns the values of this enum as an array, suitable for insertion into 
	 * a {@link DropdownField}
	 *
	 * @param boolean
	 *
	 * @return array
	 */
	public function enumValues($hasEmpty = false) {
		$locale = i18n::get_locale();
		$class = $this->enum_class;
		$enum = $class::get()->filter('Locale', $locale)->filter('Active', 1)->map('Code', 'Title')->toArray();
		return ($hasEmpty) 
			? array_merge(array('' => ''), $enum) 
			: $enum;
	}
	
	/**
	 * Returns the title
	 */
	public function Title($class = null) {
		if($class){
			$this->enum_class = $class;
		}
		$enum = $this->enumValues();
		return isset($enum[$this->value]) ? $enum[$this->value] : $this->value;
	}
}
